package com.beeasy.hzbpm.ctrl;

import cn.hutool.core.util.StrUtil;
import com.beeasy.hzbpm.util.Result;
import com.github.llyb120.json.Arr;
import com.github.llyb120.json.Json;
import com.github.llyb120.json.Obj;

import java.util.List;

import static com.beeasy.hzbpm.service.WorkService.work;
import static com.github.llyb120.json.Json.a;

public class org {

    public Result all(String type) {
        List<Obj> list;
        switch (type) {
//            case "q":
//                list = sqlManager.execute(new SQLReady("select name as text, full_name, id, parent_id,type from t_org_ext where type = 'QUARTERS' or type = 'DEPARTMENT'"), Obj.class);
//                Arr tree = Json.tree(list, "parent_id", "id");
//                return Result.ok(tree);

            case "r":
                list = work.getRoleList();
//                list = sqlManager.execute(new SQLReady("select name as text, id, parent_id,type from t_org where type = 'ROLE'"), Obj.class);
                return Result.ok(list);

            case "d":
                list = work.getDepList();
//                    sqlManager.execute(new SQLReady("select name as text, id, parent_id,type from t_org where type = 'DEPARTMENT'"), Obj.class);
                Arr tree = Json.toTree(list, "parent_id", "id");
                return Result.ok(tree);
        }
        return null;
    }

//    public Result getUser(String oid) {
//        return Result.ok(sqlManager.execute(new SQLReady("SELECT u.id,u.ACC_CODE,u.PHONE,u.true_name as name FROM DB2INST1.T_USER_ORG o inner join t_user u on o.uid=u.id and o.oid=" + oid), Obj.class));
//    }
//
//
    public Result list(String type) {
        List<Obj> list = null;
        if (StrUtil.isBlank(type)) {
            type = "DEPARTMENT";
        }
        if(type.equals("ROLE")){
            list = work.getRoleList();
        } else if(type.equals("DEPARTMENT")){
            list = work.getDepList();
        }
//            sql = String.format("select name as text, id, parent_id, type from t_org where type = '%s'", type);
//        list = sqlManager.execute(new SQLReady(sql), Obj.class);
        if (list == null) {
            return Result.ok(a());
        }
        return Result.ok(menu.tree(list, "parent_id", "id"));
    }
//
//    public Result one() {
//        List<Obj> list = sqlManager.execute(new SQLReady("select * from t_org where id = ?", $get.s("id")), Obj.class);
//        //附加关联的人
//        Obj item = list.isEmpty() ? null : list.get(0);
//        if (item == null) {
//            return Result.ok(item);
//        }
//        List<Obj> users = sqlManager.select("workflow.查找部门人员-新版关联", Obj.class, o("id", item.s("id")));
//        Obj us = o();
//        Obj ms = o();
//        Obj tms0 = o();
//        Obj tms1 = o();
//        for (Obj user : users) {
//            switch (user.s("type")) {
//                case "USER":
//                    us.put(user.s("uid"), user.s("utname"));
//                    break;
//
//                case "MANAGER":
//                    ms.put(user.s("uid"), user.s("utname"));
//                    break;
//
//                case "TOP_MANAGER0":
//                    tms0.put(user.s("uid"), user.s("utname"));
//                    break;
//
//                case "TOP_MANAGER1":
//                    tms1.put(user.s("uid"), user.s("utname"));
//                    break;
//            }
//        }
//        item.put("us", us);
//        item.put("ms", ms);
//        item.put("tms0", tms0);
//        item.put("tms1", tms1);
//        return Result.ok(item);
//    }
//
    public Object dus(String id) {
        return Result.ok(work.getDepUsersNew(id));
//        return Result.ok(
//                sqlManager.select("workflow.查找部门人员-新版关联", Obj.class, o("id", id, "type", "USER"))
//        );
    }

    public Object rus(String id) {
        return Result.ok(work.getRoleUsersNew(id));
//        return Result.ok(
//                sqlManager.execute(new SQLReady("select uid,uname,utname,otype from t_org_user where oid = ?", id), Obj.class)
//        );
    }
//
//
//    @Deprecated
//    public Object appRus() {
//        List<Obj> useResulet = new ArrayList<>();
//        List<Obj> resulet = new ArrayList<>();
//        List<Obj> list = sqlManager.execute(new SQLReady("select name as text, id, parent_id, type from t_org where type = 'ROLE'"), Obj.class);
//        List<Obj> depList = sqlManager.execute(new SQLReady("select name as text, id, parent_id, type from t_org where type = 'DEPARTMENT'"), Obj.class);
//
//        List<Obj> depResult = new ArrayList<>();
//        childTree(depList,depResult);
//
//        for (int i = 0; i < list.size(); i++) {
//            Obj obj = list.get(i);
//            List<Obj> cusList = sqlManager.execute(new SQLReady("select uid,uname,utname,otype from t_org_user" +
//                    " where oid = ?", list.get(i).get("id")), Obj.class);
//            obj.put("userChild", cusList);
//            useResulet.add(obj);
//        }
//        Obj use = new Obj();
//        use.put("ROLE",useResulet);
//        Obj dep = new Obj();
//        dep.put("DEPARTMENT",depResult);
//        resulet.add(use);
//        resulet.add(dep);
//
//        return Result.ok(Json.tree(resulet, "parent_id", "id"));
//    }
////
////
////
//    @Deprecated
//    private void  childTree( List<Obj> depList, List<Obj> depResult){
//        for (int i = 0; i < depList.size(); i++) {
//            Obj obj = depList.get(i);
//            Obj newObj = new Obj();
//            newObj.put("text", obj.get("text"));
//            newObj.put("id", obj.get("id"));
//            newObj.put("depChild", sqlManager.select("workflow.查找部门人员-新版关联", Obj.class, o("id", obj.get("id"), "type", "USER")));
//            depResult.add(newObj);
//            if(null != obj.get("children")){
//                childTree(( List<Obj>) obj.get("children"),depResult);
//            }
//        }
//    }
//
//
//    /**
//     * 乾坤大挪移
//     *
//     * @param id
//     * @param pid
//     * @return
//     */
//    public Object move(String id, String pid) {
//        int ret = sqlManager.executeUpdate(new SQLReady("update t_org set parent_id = ? where id = ?", pid, id));
//        return Result.ok(ret > 0);
//    }
//
//    public Object del(String id) {
//        //有下级部门或者岗位的禁止删除
//        List<Obj> list = sqlManager.execute(new SQLReady("select count(1) from t_org where parent_id = ?", id), Obj.class);
//        int count = list.get(0).i("1");
//        if (count > 0) {
//            return Result.error("还有下级分支，无法删除");
//        }
//        sqlManager.deleteById(Org.class, id);
//        return Result.ok();
//    }
//
//
//    public Object save(Org body) {
//        if (StrUtil.isBlank(body.name)) {
//            throw new BpmException("部门名不能为空");
//        }
//        body.type = "DEPARTMENT";
//        if (body.id == null) {
//            body.id = IdUtil.createSnowflake(0, 0).nextId();
//            sqlManager.insert(body);
//        } else {
//            sqlManager.lambdaQuery(Org.class)
//                    .andEq("id", body.id)
//                    .updateSelective(o(
//                            "name", body.name,
//                            "info", body.info,
//                            "sort", body.sort
//                    ));
//        }
//        //处理保存的人
//        List<Object[]> args = new ArrayList<>();
//        SQLBatchReady ready = new SQLBatchReady("insert into t_user_dep(did,uid,type)values(?,?,?)");
//        String[] types = {"USER", "MANAGER", "TOP_MANAGER0", "TOP_MANAGER1"};
//        String[] keys = {"us", "ms", "tms0", "tms1"};
//        int i = 0;
//        for (String type : types) {
//            String key = keys[i++];
//            if ($request.containsKey(key)) {
//                Obj o = $request.o(key);
//                args.addAll(o.keySet().stream()
//                        .map(e -> new Object[]{body.id, e, type})
//                        .collect(Collectors.toList()));
//            }
//        }
//        sqlManager.executeUpdate(new SQLReady("delete from t_user_dep where did = ?", body.id));
//        if (!args.isEmpty()) {
//            ready.setArgs(args);
//            sqlManager.executeBatchUpdate(ready);
//        }
//        return Result.ok(body);
//    }
//
    public Object users(String keyword) {
        if (StrUtil.isEmpty(keyword)) {
            keyword = "";
        }
        return Result.ok(work.searchUserByKeyword(keyword));

//        keyword = "%" + keyword + "%";
//        return Result.ok(sqlManager.execute(new SQLReady("select id as uid,true_name as utname from t_user where username like ? or true_name like ? fetch first 30 rows only", keyword, keyword), Obj.class));
    }
//
//    /**
//     * @param utname 名称
//     * @param list   角色list
//     * @param did    部门id
//     * @return
//     */
//    public Object appSerach(String utname, String[] list, String did) {
//        return Result.ok(
//                sqlManager.select("workflow.查找人员-APP", Obj.class, o("utname", utname, "oid", list, "did", did))
//        );
//    }
//
//
//    //APP选人，初始化所有人员列表
//    public Object appUser() {
//        return Result.ok(sqlManager.execute(new SQLReady("select id as uid,true_name as utname from t_user"), Obj.class));
//    }
//
//
//    /**
//     * 同步所有部门的人员
//     *
//     * @return
//     */
//    public Object sync() {
//        List<Obj> list = sqlManager.execute(new SQLReady("select * from t_org_user where otype = 'QUARTERS'"), Obj.class);
//        sqlManager.executeUpdate(new SQLReady("delete from t_user_dep where type = 'USER'"));
//        Obj cache = o();
//        for (Obj obj : list) {
//            Arr uids = cache.a(obj.s("pid"));
//            if (uids == null) {
//                cache.put(obj.s("pid"), uids = a());
//            }
//            uids.add(obj.s("uid"));
//        }
//
//        SQLBatchReady ready = new SQLBatchReady("insert into t_user_dep(did,uid,type)values(?,?,?)");
//        List<Object[]> args = new ArrayList<>();
//        for (Map.Entry<String, Object> entry : cache.entrySet()) {
//            //distinct
//            List<String> uids = (List<String>) entry.getValue();
//            uids = uids.stream()
//                    .distinct().collect(Collectors.toList());
//            for (String uid : uids) {
//                args.add(new Object[]{entry.getKey(), uid, "USER"});
//            }
//        }
//        ready.setArgs(args);
//        sqlManager.executeBatchUpdate(ready);
//        return Result.ok();
//    }


//    public Object getUserByDept(String[] pid, String type){
//        if(null == pid){
//            return Result.ok();
//        }
//        switch (type) {
//            case "d":
//                List<String> pids = Arrays.asList(pid);
//                String id = pids.stream().map(p -> "'" + p + "'").collect(Collectors.joining(","));
//                return Result.ok(sqlManager.execute(new SQLReady(String.format("select * from t_org_user where pid in (%s)",pids.isEmpty() ? "-1": id)),Obj.class));
//            case "r":
//                List<String> rids = Arrays.asList(pid);
//                String rid = rids.stream().map(r -> "'" + r + "'").collect(Collectors.joining(","));
//                return Result.ok(sqlManager.execute(new SQLReady(String.format("select  id as uid,true_name as utname,acc_code as uname from t_user u where 1 = 1 and exists(select 1 from t_user_org where uid = u.id and oid in (%s)) ",rids.isEmpty() ? "-1": rid)),Obj.class));
//                default:
//                    return Result.ok();
//
//        }
//    }
}
